package com.itheima.reggie.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import okhttp3.OkHttpClient;
import okhttp3.Request;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 文件上传服务器
 *
 * @Name : QiNiuUtil
 * @Author : WuQiang
 * @Date : 2022-08-14 16:30
 * @Description : 文件上传服务器
 */
public class QiNiuUtil {

    /**
     * 文件上传工具类
     *
     * @param fileCount 文件字节数组
     * @param fileName  文件名称
     */
    public static void upload(byte[] fileCount, String fileName) {
        //构造一个带指定 Region 对象的配置类:设置上传空间华东浙江2
        Configuration cfg = new Configuration(Region.regionCnEast2());
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = "b14aENLR4e8XQ903rFKOpGQnhNuCOaYTiaW6EQiw";
        String secretKey = "MCAtEEYpoWAEj8B6rUOE7dXz5vAYu-ACEpAfFzKZ";
        String bucket = "wuqiang-reggie3";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = fileName;

        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        try {
            Response response = uploadManager.put(fileCount, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }

    /**
     * 文件下载工具类
     *
     * @param fileName 文件名称
     * @return
     */
    public static InputStream download(String fileName) {
        String domainOfBucket = "http://riw9z4x37.bkt.clouddn.com";
        String encodedFileName = null;
        try {
            encodedFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String finalUrl = String.format("%s/%s", domainOfBucket, encodedFileName);


        //将文件链接地址转换成流信息
        OkHttpClient okHttpClient = new OkHttpClient();
        //创建请求对象
        Request request = new Request.Builder().get().url(finalUrl).build();
        okhttp3.Response response =null;
        try {
            // 模拟发送一个请求！
            response = okHttpClient.newCall(request).execute();
            // 请求成功！
            if (response.isSuccessful()){
                InputStream inputStream = response.body().byteStream();
                return inputStream;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }
}
